const { executeQuery } = require('../config/dbConfig');
const { generateToken } = require('../utils/jwt');
const { generateAvatarSVG } = require('../utils/avatar');

class AdminService {
  // 管理员登录
  async login(username, password, remember = false) {
    const admins = await executeQuery(
      `SELECT a.*, GROUP_CONCAT(p.id) as permission_ids, 
       GROUP_CONCAT(p.name) as permission_names,
       GROUP_CONCAT(p.code) as permission_codes
       FROM admins a
       LEFT JOIN admin_permissions ap ON a.id = ap.admin_id
       LEFT JOIN permissions p ON ap.permission_id = p.id
       WHERE a.username = ? AND a.password = ? AND a.status = 1
       GROUP BY a.id`,
      [username, password]
    );

    if (admins.length === 0) {
      throw new Error('用户名或密码错误');
    }

    const admin = admins[0];
    
    // 格式化管理员信息
    const formattedAdmin = {
      ...admin,
      permissions: admin.permission_codes ? 
        admin.permission_codes.split(',').map((code, i) => ({
          id: Number(admin.permission_ids.split(',')[i]),
          name: admin.permission_names.split(',')[i],
          code
        })) : [],
      is_super: Boolean(admin.is_super),
      status: Number(admin.status)
    };
    
    const token = generateToken({
      id: admin.id,
      username: admin.username,
      role: 'admin',
      is_super: admin.is_super
    }, remember);

    return { admin: formattedAdmin, token };
  }

  // 获取管理员列表
  async getAdminList() {
    const admins = await executeQuery(
      `SELECT a.id, a.username, a.nickname, a.is_super, a.status, a.created_at,
       GROUP_CONCAT(p.id) as permission_ids, GROUP_CONCAT(p.name) as permission_names,
       GROUP_CONCAT(p.code) as permission_codes
       FROM admins a
       LEFT JOIN admin_permissions ap ON a.id = ap.admin_id
       LEFT JOIN permissions p ON ap.permission_id = p.id
       GROUP BY a.id
       ORDER BY a.created_at ASC`
    );

    // 权限标签类型映射
    const permissionTypeMap = {
      'super_admin': 'danger',    
      'dashboard': 'info',        
      'book_manage': 'success',   
      'report_manage': 'warning',
      'user_manage': ''          
    };

    // 格式化数据
    return admins.map(admin => ({
      ...admin,
      permissions: admin.is_super ? 
        [{ id: 0, name: '系统管理员', type: 'danger' }] :
        (admin.permission_codes ? 
          admin.permission_codes.split(',').map((code, i) => ({
            id: Number(admin.permission_ids.split(',')[i]),
            name: admin.permission_names.split(',')[i],
            code,
            type: permissionTypeMap[code] || ''
          })) : []),
      is_super: Boolean(admin.is_super),
      status: Number(admin.status)
    }));
  }

  // 创建管理员
  async addAdmin(adminData) {
    // 检查用户名是否存在
    const existingAdmin = await executeQuery(
      'SELECT id FROM admins WHERE username = ?',
      [adminData.username]
    );

    if (existingAdmin.length > 0) {
      throw new Error('该管理员已存在');
    }

    // 生成默认头像
    const avatarData = generateAvatarSVG(adminData.nickname);

    const result = await executeQuery(
      `INSERT INTO admins (username, password, nickname, avatar_type, avatar_data, is_super) 
       VALUES (?, ?, ?, 'default', ?, ?)`,
      [
        adminData.username,
        adminData.password,
        adminData.nickname,
        avatarData,
        adminData.isSuper || 0
      ]
    );

    return result.insertId;
  }

  // 更新当前管理员密码
  async updatePassword(id, oldPassword, newPassword) {
    const admins = await executeQuery(
      'SELECT id FROM admins WHERE id = ? AND password = ?',
      [id, oldPassword]
    );

    if (admins.length === 0) {
      throw new Error('原密码错误');
    }

    const result = await executeQuery(
      'UPDATE admins SET password = ? WHERE id = ?',
      [newPassword, id]
    );

    return result.affectedRows > 0;
  }

  // 更新管理员信息
  async updateAdmin(id, data) {
    const updateFields = [];
    const updateValues = [];

    if (data.username) {
      // 检查新用户名是否已被其他管理员使用
      const existingAdmin = await executeQuery(
        'SELECT id FROM admins WHERE username = ? AND id != ?',
        [data.username, id]
      );

      if (existingAdmin.length > 0) {
        throw new Error('该管理员已存在');
      }

      updateFields.push('username = ?');
      updateValues.push(data.username);
    }
    if (data.nickname) {
      updateFields.push('nickname = ?');
      updateValues.push(data.nickname);
    }
    if (data.status !== undefined) {
      updateFields.push('status = ?');
      updateValues.push(data.status);
    }
    if (data.avatar_type) {
      updateFields.push('avatar_type = ?');
      updateValues.push(data.avatar_type);
    }
    if (data.avatar_data) {
      updateFields.push('avatar_data = ?');
      updateValues.push(data.avatar_data);
    }

    // 添加更新时间
    updateFields.push('updated_at = CURRENT_TIMESTAMP');

    // 添加 id 到参数数组
    updateValues.push(id);
    
    await executeQuery(
      `UPDATE admins SET ${updateFields.join(', ')} WHERE id = ?`,
      updateValues
    );
    
    return true;
  }

  // 删除管理员
  async deleteAdmin(id) {
    await executeQuery(
      'DELETE FROM admins WHERE id = ?',
      [id]
    );

    return true;
  }

  // 获取用户列表
  async getUserList() {
    const users = await executeQuery(
      `SELECT u.*, 
        (SELECT COUNT(*) FROM posts WHERE user_id = u.id) as post_count 
       FROM users u`
    );
    return users;
  }

  // 创建用户
  async addUser(userData) {
    // 检查用户名是否存在
    const existingUser = await executeQuery(
      'SELECT id FROM users WHERE username = ?',
      [userData.username]
    );

    if (existingUser.length > 0) {
      throw new Error('用户名已存在');
    }

    // 生成默认头像
    const avatarData = generateAvatarSVG(userData.nickname);

    const result = await executeQuery(
      `INSERT INTO users (username, password, nickname, avatar_type, avatar_data) 
       VALUES (?, ?, ?, 'default', ?)`,
      [userData.username, userData.password, userData.nickname, avatarData]
    );

    return result.insertId;
  }

  // 更新用户信息
  async updateUser(id, userData) {
    const updateFields = [];
    const updateValues = [];
    
    if (userData.username) {
      // 检查新用户名是否已被其他用户使用
      const existingUser = await executeQuery(
        'SELECT id FROM users WHERE username = ? AND id != ?',
        [userData.username, id]
      );

      if (existingUser.length > 0) {
        throw new Error('用户名已存在');
      }

      updateFields.push('username = ?');
      updateValues.push(userData.username);
    }
    if (userData.password) {
      updateFields.push('password = ?');
      updateValues.push(userData.password);
    }
    
    // 如果没有要更新的字段，直接返回
    if (updateFields.length === 0) {
      return true;
    }
    
    updateValues.push(id);
    
    await executeQuery(
      `UPDATE users SET ${updateFields.join(', ')} WHERE id = ?`,
      updateValues
    );
    
    return true;
  }

  // 删除用户
  async deleteUser(id) {
    await executeQuery(
      'DELETE FROM users WHERE id = ?',
      [id]
    );

    return true;
  }

  // 更新用户状态
  async updateUserStatus(id, status) {
    await executeQuery(
      'UPDATE users SET status = ? WHERE id = ?',
      [status, id]
    );
    
    return true;
  }

  // // 获取待审核的书籍列表
  // async getPendingBooks() {
  //   const books = await executeQuery(
  //     `SELECT p.*, u.nickname as author_name,
  //      (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as likes_count,
  //      (SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comments_count
  //      FROM posts p
  //      LEFT JOIN users u ON p.user_id = u.id
  //      WHERE p.status = 'pending'
  //      ORDER BY p.created_at DESC`
  //   );
  //   return books;
  // }

  // // 审核通过书籍
  // async approveBook(bookId, adminId) {
  //   const result = await executeQuery(
  //     `UPDATE posts SET 
  //      status = 'approved',
  //      approved_at = CURRENT_TIMESTAMP,
  //      approved_by = ?
  //      WHERE id = ? AND status = 'pending'`,
  //     [adminId, bookId]
  //   );

  //   if (result.affectedRows === 0) {
  //     throw new Error('书籍不存在或已被处理');
  //   }

  //   return true;
  // }

  // // 驳回书籍
  // async rejectBook(bookId, adminId, rejectReason) {
  //   const result = await executeQuery(
  //     `UPDATE posts SET 
  //      status = 'rejected',
  //      reject_reason = ?,
  //      rejected_at = CURRENT_TIMESTAMP,
  //      rejected_by = ?
  //      WHERE id = ? AND status = 'pending'`,
  //     [rejectReason, adminId, bookId]
  //   );

  //   if (result.affectedRows === 0) {
  //     throw new Error('书籍不存在或已被处理');
  //   }

  //   return true;
  // }

  // 获取用户发布的书籍
  async getUserPosts(userId) {
    const posts = await executeQuery(
      `SELECT p.id, p.title, p.author, p.thoughts, p.created_at, u.nickname as author_name,
       (SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
       (SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comment_count,
       (SELECT AVG(score) FROM ratings WHERE post_id = p.id) as avg_rating
       FROM posts p
       LEFT JOIN users u ON p.user_id = u.id
       WHERE p.user_id = ?
       ORDER BY p.created_at DESC`,
      [userId]
    );
    // 格式化数据
    return posts.map(post => ({
      ...post,
      like_count: Number(post.like_count),
      comment_count: Number(post.comment_count),
      avg_rating: post.avg_rating ? Number(post.avg_rating) : 0
    }));
  }

  /**
   * 更新管理员权限
   */
  async updateAdminPermissions(adminId, permissions) {
    // 检查是否是系统管理员
    const admin = await executeQuery('SELECT * FROM admins WHERE id = ?', [adminId]);
    if (admin[0]?.is_super) {
      throw new Error('系统管理员权限不可修改');
    }

    // 删除原有权限
    await executeQuery('DELETE FROM admin_permissions WHERE admin_id = ?', [adminId]);

    // 插入新权限
    if (permissions && permissions.length > 0) {
      for (const permId of permissions) {
        await executeQuery(
          'INSERT INTO admin_permissions (admin_id, permission_id) VALUES (?, ?)',
          [adminId, permId]
        );
      }
    }

    return true;
  }
}

module.exports = new AdminService(); 